<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      :btn-list="fullInfo.btnList"
      @returnBack="$emit('returnModify')"
    >
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
            @handleEvent="changeHandle"
          >
            <template v-slot:form-deptName>
              <el-input
                v-if="isSpecialEdit === 1"
                v-model="formInfo.data.deptName"
                disabled
              ></el-input>
              <el-input
                v-else
                v-model="formInfo.data.deptName"
                class="not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择部门"
              >
                <template #append>
                  <el-icon @click="openDeptWindow"><MoreFilled /></el-icon>
                  <!-- <el-button
                    style="border-color: #dcdfe6"
                    icon="More"
                    @click="openDeptWindow"
                  /> -->
                </template>
              </el-input>
            </template>
            <template v-slot:form-receiveAddressValue>
              <el-input
                v-if="isSpecialEdit === 1"
                v-model="formInfo.data.receiveAddressValue"
                disabled
              ></el-input>
              <el-input
                v-else
                v-model="formInfo.data.receiveAddressValue"
                class="not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择收货地址"
              >
                <template #append>
                  <el-icon @click="openReceiveAddressWindow"
                    ><MoreFilled
                  /></el-icon>
                </template>
              </el-input>
            </template>
          </page-form>
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="$t('detailInfo')"></Tooltip>
          <div class="model-tips">
            (证照：<span>近效期</span>
            <span class="model-tips-nearly"></span>
          </div>
          <div class="model-tips">
            <span>过期</span>
            <span class="model-tips-expire"></span>)
          </div>
        </div>
        <div class="model-panel-body">
          <div class="filter-wrapper">
            <!-- 条件栏 -->
            <page-filter
              v-if="!isReadOnly"
              v-model:query="filterInfo.query"
              :filter-list="filterInfo.list"
            >
              <template v-slot:filter-addProduct>
                <el-button :disabled="!canAddProduct" @click="addProduct"
                  >添加产品</el-button
                >
              </template>
              <template v-slot:filter-addProductByContract>
                <el-button
                  :disabled="!canAddProductByContranct"
                  @click="addProductByContract"
                  >根据合同添加产品</el-button
                >
              </template>
              <template v-slot:filter-removeProduct>
                <el-button
                  :disabled="!canRemoveProduct"
                  @click="removeProduct()"
                  >删除产品</el-button
                >
              </template>
              <template v-slot:filter-selectTemplate>
                <el-button
                  :disabled="!formInfo.data.deptId || isSpecialEdit === 1"
                  @click="selectTemplate"
                  >选择模板</el-button
                >
              </template>
            </page-filter>
            <div class="display-flex">
              <el-button @click="preferenceInfo.visible = true"
                >偏好设置</el-button
              >
            </div>
          </div>
          <div class="flex_full_item">
            <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
              <!-- 表格 -->
              <page-table
                ref="table"
                class="table-scroll-hidden"
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :tab-index="false"
                :query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :row-class-name="tableRowClassName"
                :cell-class-name="tableCellClassName"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-qty="scope">
                  <el-form-item class="margin-bottom">
                    <div class="page-table-input-number-wrapper">
                      <div class="page-table-input-number-left">
                        <div class="page-table-input-number-item">
                          <el-form-item
                            :prop="`data.${scope.$index}.largeUnitQty`"
                            :rules="
                              scope.$index >= 0
                                ? [
                                    {
                                      validator: $validate.positiveAndZero,
                                      trigger: 'blur',
                                    },
                                  ]
                                : []
                            "
                          >
                            <el-input-number
                              style="width: 100%; margintop: 18px"
                              v-model.lazy="scope.row.largeUnitQty"
                              clearable
                              controls-position="right"
                              :precision="
                                scope.row.qtyOperateMode === 0 ||
                                scope.row.qtyOperateMode === 2
                                  ? 0
                                  : systemConfig.qty_show_precision
                              "
                              @change="
                                changeLarge(
                                  $event,
                                  `data.${scope.$index}.largeUnitQty`
                                )
                              "
                              :min="0"
                              :max="largeMax(scope.row)"
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            {{ scope.row.unitName }}
                          </div>
                        </div>
                        <div
                          class="page-table-input-number-item"
                          v-if="
                            scope.row.unitConvertCoefficient > 1 &&
                            scope.row.qtyOperateMode === 2
                          "
                        >
                          <el-form-item>
                            <el-input-number
                              style="width: 100%; margintop: 18px"
                              v-model.lazy="scope.row.smallUnitQty"
                              clearable
                              controls-position="right"
                              :precision="0"
                              :min="0"
                              :max="smallMax(scope.row)"
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            {{ scope.row.calcUnitName }}
                          </div>
                        </div>
                      </div>
                      <div
                        class="page-table-input-number-right"
                        v-if="scope.row.qtyOperateMode === 2"
                      >
                        {{ $fn.qtyFormatter(scope.row.qty) }}
                      </div>
                    </div>
                  </el-form-item>
                </template>
                <template v-slot:col-price="scope">
                  <p>{{ scope.row.price }}</p>
                  <p
                    style="color: red"
                    v-if="
                      scope.row.isLimitPrice == 1 &&
                      scope.row.price > scope.row.purchaseLimitPrice
                    "
                  >
                    超过产品限价:{{ scope.row.purchaseLimitPrice }}
                  </p>
                </template>
              </page-table>
            </el-form>
          </div>

          <!-- 选择产品 -->
          <NewSelectProduct
            v-if="productInfo.visible"
            v-model:show-dialog="productInfo.visible"
            :query="productInfo.query.queryMap"
            :query-params="productInfo.query.queryParams"
            :api="productInfo.api"
            :notDefaultProductSupplier="true"
            :table-key="productInfo.tableKey"
            @callback="selectProductCallback"
          />

          <!-- 在供货目录中 根据产品选择供应商 -->
          <select-supplier
            v-if="selectProductSupplier.visible"
            v-model:show-dialog="selectProductSupplier.visible"
            :query="selectProductSupplier.query"
            :check-box="false"
            :highlight-row="true"
            :api="selectProductSupplier.api"
            @callback="selectProductSupplierCallback"
          />
          <!-- 选择收货地址 -->
          <select-receive-address
            v-if="selectReceiveAddressInfo.visible"
            v-model:show-dialog="selectReceiveAddressInfo.visible"
            :query="selectReceiveAddressInfo.query"
            :check-box="false"
            :highlight-row="true"
            @callback="selectReceiveAddressCallback"
          />
          <!-- 选择部门 -->
          <select-dept
            v-if="selectDeptInfo.visible"
            v-model:show-dialog="selectDeptInfo.visible"
            :query="selectDeptInfo.query"
            :check-box="false"
            :highlight-row="true"
            :saveEmpty="true"
            @callback="selectDeptCallback"
          />
          <select-purch-template
            v-if="purchTemplateInfo.visible"
            v-model:show-dialog="purchTemplateInfo.visible"
            :check-box="true"
            :tab-index="true"
            :highlight-row="false"
            :query="purchTemplateInfo.query"
            @callback="selectPurchTemplateCallback"
          />
          <SetPreferenceNoQuery
            v-if="preferenceInfo.visible"
            v-model:visible="preferenceInfo.visible"
            :searchList="filterInfo.searchList"
            :fieldList="tableInfo.fieldList"
            :customizeUserVO="filterInfo.query.customizeUserVO"
            :groupLevelShow="false"
            @callback="setPreferenceCallback"
          />
          <SelectContract
            v-if="contractInfo.visible"
            v-model:showDialog="contractInfo.visible"
            :checkBox="true"
            :query="contractInfo.query"
            :data="contractInfo.data"
            :changeContract="contractInfo.changeContract"
            :highlightRow="true"
            :saveEmpty="false"
            :isCopy="isCopy"
            @callback="selectContractCallBack"
          />
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-body">
          <el-collapse v-model="activeNames" class="collapseBody">
            <el-collapse-item title="操作流水" name="1">
              <page-table
                ref="table"
                class="table-scroll-hidden"
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :tab-index="false"
                :query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :row-class-name="tableRowClassName"
                :cell-class-name="tableCellClassName"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-qty="scope">
                  <el-form-item class="margin-bottom">
                    <div class="page-table-input-number-wrapper">
                      <div class="page-table-input-number-left">
                        <div class="page-table-input-number-item">
                          <el-form-item
                            :prop="`data.${scope.$index}.largeUnitQty`"
                            :rules="
                              scope.$index >= 0
                                ? [
                                    {
                                      validator: $validate.positiveAndZero,
                                      trigger: 'blur',
                                    },
                                  ]
                                : []
                            "
                          >
                            <el-input-number
                              style="width: 100%; margintop: 18px"
                              v-model.lazy="scope.row.largeUnitQty"
                              clearable
                              controls-position="right"
                              :precision="
                                scope.row.qtyOperateMode === 0 ||
                                scope.row.qtyOperateMode === 2
                                  ? 0
                                  : systemConfig.qty_show_precision
                              "
                              @change="
                                changeLarge(
                                  $event,
                                  `data.${scope.$index}.largeUnitQty`
                                )
                              "
                              :min="0"
                              :max="largeMax(scope.row)"
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            {{ scope.row.unitName }}
                          </div>
                        </div>
                        <div
                          class="page-table-input-number-item"
                          v-if="
                            scope.row.unitConvertCoefficient > 1 &&
                            scope.row.qtyOperateMode === 2
                          "
                        >
                          <el-form-item>
                            <el-input-number
                              style="width: 100%; margintop: 18px"
                              v-model.lazy="scope.row.smallUnitQty"
                              clearable
                              controls-position="right"
                              :precision="0"
                              :min="0"
                              :max="smallMax(scope.row)"
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            {{ scope.row.calcUnitName }}
                          </div>
                        </div>
                      </div>
                      <div
                        class="page-table-input-number-right"
                        v-if="scope.row.qtyOperateMode === 2"
                      >
                        {{ $fn.qtyFormatter(scope.row.qty) }}
                      </div>
                    </div>
                  </el-form-item>
                </template>
                <template v-slot:col-price="scope">
                  <p>{{ scope.row.price }}</p>
                  <p
                    style="color: red"
                    v-if="
                      scope.row.isLimitPrice == 1 &&
                      scope.row.price > scope.row.purchaseLimitPrice
                    "
                  >
                    超过产品限价:{{ scope.row.purchaseLimitPrice }}
                  </p>
                </template>
              </page-table>
            </el-collapse-item>
          </el-collapse>
        </div>
      </div>
    </NewFullScreen>
  </div>
</template>

<script setup name="purchOrderDemo">
import {
  createPurchOrder,
  updatePurchOrder,
  purchOrderById,
  applicationSummaryDetailAddProduct,
  getOrdersProduct,
  getPurchTemplateDetailAll,
  applicationDetailAddProduct,
  purchOrdersDetailCustomizeListAll,
} from '@/api/purch'
import {
  getReceiveAddressPage,
  getCoreSystemConfigGetConfigValue,
  getProductCustomizeList,
  getSupplierProductPage,
} from '@/api/core'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import SelectContract from './selectContract'
import _ from 'lodash'
const SetPreferenceNoQuery = defineAsyncComponent(() =>
  import('@/components/SetPreference/setPreferenceNoQuery')
)
const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps([
  'tableKey',
  'visible',
  'title',
  'orderId',
  'isSpecialEdit',
  'isCopy',
  'purchAccording',
])

const activeNames = ref([])
const formRefs = ref([])
const purchTemplateInfo = ref({
  visible: false,
  query: {},
})
const formInfo = ref({
  ref: null,
  data: {
    deptName: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.name
      : '',
    deptId: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : '',
    supplierId: '',
    supplierName: '',
    receiveAddressValue: '',
    purchProductType: 1,
    purchAccording:
      props.purchAccording ||
      proxy.$store.state.permission.systemConfig.purch_according,
    createUserName: proxy.$store.state.user.userInfo.user
      ? proxy.$store.state.user.userInfo.user.name
      : '',
  },
  fieldList: [
    { label: '部门', value: 'deptName', type: 'slot' },
    {
      label: '创建人',
      value: 'createUserName',
      type: 'input',
      disabled: true,
    },
    { label: '收货地址', value: 'receiveAddressValue', type: 'slot' },
    {
      label: '是否寄售业务',
      value: 'isConsignBusiness',
      type: 'select-model',
      code: 'default_no_or_yes',
      event: 'isConsignBusiness',
      show:
        proxy.$store.state.permission.systemConfig.is_consign_business === 1 &&
        props.orderId,
    },
    {
      label: '采购依据',
      value: 'purchAccording',
      type: 'select-model',
      code: 'purch_according',
      disabled: true,
      event: 'purchAccording',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    deptName: [{ required: true, message: '请选择部门', trigger: 'change' }],
    receiveAddressValue: [
      { required: true, message: '请选择收货地址', trigger: 'change' },
    ],
    supplierName: [
      { required: true, message: '请选择供应商', trigger: 'change' },
    ],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {
      purchAccording: '',
    },
  },
  list: [
    { type: 'slot', label: '添加产品', value: 'addProduct' },

    { type: 'slot', label: '删除产品', value: 'removeProduct' },
    { type: 'slot', value: 'selectTemplate' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  selectionsCopy: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'price', show: 'false' },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  applicationFieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '切换供应商',
        event: changeSupplier,
        ifRender: ifRenderValue,
        show: true,
      },
      {
        label: '切换合同',
        event: changeContract,
        show: true,
      },
      { label: '删除产品', event: removeProduct, show: true },
    ],
  },
})
const fullInfo = ref({
  btnList: [{ label: '保存', event: save, show: true }],
})
//选择产品相关
const productInfo = ref({
  visible: false,
  api: getProductCustomizeList,
  tableKey:
    'productPageForPurchOrder-com.slip.spd.entity.vo.core.CoreProductVONew',
  query: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: null,
      },
      status: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      supplierId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      productId: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: null,
      },
      putShelfStatus: {
        asTbName: 'core_product_new',
        columnName: 'put_shelf_status',
        queryResource: 0,
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 1,
      },
      type: {
        asTbName: 'core_product_new',
        columnName: 'type',
        queryResource: 0,
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
      isConsignment: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
    },
    queryParams: {
      checkDeptProduct: 1,
      selectStockTotalQty: 1,
    },
  },
  searchList: [],
})
const applicationProductInfo = ref({
  visible: false,
  api: '', //产品数量不对
  query: {
    deptId: '',
  },
})
const selectSupplierInfo = ref({
  visible: false,
  query: {
    supplierAuth: 'supplierId',
  },
})
//在供货目录中 根据产品id选择供应商
const selectProductSupplier = ref({
  visible: false,
  index: '',
  api: getSupplierProductPage,
  query: {
    id: '',
    searchType: 'org',
    searchField: 'supplierId',
    supplierAuth: 'supplierId',
  },
})
const selectRow = ref('')
const selectReceiveAddressInfo = ref({
  visible: false,
  query: {},
})
const selectDeptInfo = ref({
  visible: false,
  query: {
    deptAuth: 'id',
  },
})
const preferenceInfo = ref({
  visible: false,
})
const contractInfo = ref({
  visible: false,
  query: {},
  data: [],
  changeContract: false,
})
const tmpData = ref([])
//用于显示取值
const showSelectOrder = ref(false)
const mergedPurchIds = ref('')
const disabledTemplateBtn = ref(false)
const defaultSelect = ref([])
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const licencesSystemConfig = ref('')
const defaultSupplier = ref(true)

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
const isUpdate = computed(() => {
  return formInfo.value.data.id !== undefined
})
const isReadOnly = computed(() => {
  //确定是否为提交状态
  return !formInfo.value.data.status === 1
})
const canAddProduct = computed(() => {
  return formInfo.value.data.deptId && props.isSpecialEdit !== 1
})
const canAddProductByContranct = computed(() => {
  return (
    formInfo.value.data.deptId &&
    props.isSpecialEdit !== 1 &&
    parseInt(props.purchAccording) === 2
  )
})
const canRemoveProduct = computed(() => {
  return tableInfo.value.selections.length && props.isSpecialEdit !== 1
})

watch(
  () => tableInfo.value.data,
  () => {
    tableInfo.value.data.forEach((row) => {
      let smallUnitQty = parseFloat(row.smallUnitQty || 0)
      let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
      let largeUnitQty = parseFloat(row.largeUnitQty || 0)
      let calcQty = proxy.$fn.accAdd(
        proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
        smallUnitQty
      )
      let qty = proxy.$fn.qtyFormatter(
        proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
      )
      row['calcQty'] = calcQty
      row['qty'] = qty
      row.sumAmount = proxy.$fn.accMul(
        proxy.$fn.accAdd(
          proxy.$fn.accDiv(smallUnitQty, unitConvertCoefficient),
          largeUnitQty
        ),
        parseFloat(row.price == null ? 0 : row.price)
      )
      if (
        defaultSupplier.value &&
        props.title !== '修改采购单' &&
        props.title !== '拷贝采购单' &&
        props.purchAccording === 1
      ) {
        row.supplierId = row.defaultSupplierId
        row.supplierName = row.defaultSupplierName
      }
    })
  },
  {
    deep: true,
  }
)

onMounted(() => {
  getValueList()
  formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  //请求默认地址并回填
  getReceiveAddressPage({ isDefault: '1' }).then((resp) => {
    if (resp && resp.success && resp.data[0]) {
      formInfo.value.data.receiveProvince = resp.data[0].province
      formInfo.value.data.receiveCity = resp.data[0].city
      formInfo.value.data.receiveCounty = resp.data[0].county
      formInfo.value.data.receiveAddress = resp.data[0].address
      formInfo.value.data.receiveAddressValue = resp.data[0].addressValue
      formInfo.value.data.receiveContacts = resp.data[0].contacts
      formInfo.value.data.receivePhone = resp.data[0].contactsPhone
    }
  })
})

setData()
function setData() {
  let obj = {
    qty: {
      label: '申购数量',
      value: 'qty',
      type: 'slot',
      minWidth: '250px',
      hidden: true,
    },
    price: {
      label: '单价',
      value: 'price',
      type: 'slot',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('purchOrder:price'),
      hidden: true,
    },
    sumAmount: {
      label: '总金额',
      value: 'sumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('purchOrder:price'),
      hidden: true,
    },
    defaultSupplierPrice: {
      label: '默认供应商价格',
      value: 'defaultSupplierPrice',
      type: 'column',
      permission: !proxy.$permission('purchOrder:price'),
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
  let changeContract = _.find(tableInfo.value.handle.btList, [
    'label',
    '切换合同',
  ])
  let changeSupplier = _.find(tableInfo.value.handle.btList, [
    'label',
    '切换供应商',
  ])
  changeContract.show = false
  changeSupplier.show = true
  if (parseInt(props.purchAccording) === 2) {
    filterInfo.value.list.splice(1, 0, {
      type: 'slot',
      label: '根据合同添加产品',
      value: 'addProductByContract',
    })
    changeContract.show = true
    changeSupplier.show = false
  }
}
function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(true)
    }
  })
}
function changeHandle(e, val) {
  if (e === 'isConsignBusiness') {
    tableInfo.value.data = []
    if (val == 1) {
      formInfo.value.data.isConsignBusinessValue = '是'
    } else if (val == 0) {
      formInfo.value.data.isConsignBusinessValue = '否'
    }
  } else if (e === 'purchAccording') {
    tableInfo.value.fieldList.forEach((item) => {
      if (item.value === 'quoteContractNo') {
        if (val == 2) {
          item.hidden = false
        } else {
          item.hidden = true
        }
      }
    })
  }
}
function ifRenderValue(row) {
  return (
    formInfo.value.data.summaryId == undefined ||
    formInfo.value.data.summaryId == '' ||
    formInfo.value.data.summaryId === -2
  )
}
function changeLarge(e, str) {
  proxy.$refs.tableForm.clearValidate(str)
}
function largeMax(row) {
  if (
    systemConfig.value.use_convert_count_restrict == 1 &&
    formInfo.value.data.useId &&
    (row.maxConvertCount || row.maxConvertCount === 0)
  ) {
    return parseInt((row.maxConvertCount || 0) / row.unitConvertCoefficient)
  } else {
    return 99999999
  }
}
function smallMax(row) {
  if (
    systemConfig.value.use_convert_count_restrict == 1 &&
    formInfo.value.data.useId &&
    (row.maxConvertCount || row.maxConvertCount === 0)
  ) {
    return parseInt((row.maxConvertCount || 0) % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
// 触发事件
function handleEvent(event, data) {
  const _tableInfo = tableInfo.value
  switch (event) {
    case 'tableCheck':
      _tableInfo.selections = [...data]
      break
  }
}
//切换供应商
function changeSupplier(row, index) {
  selectProductSupplier.value.visible = true
  selectProductSupplier.value.query.productId = row.productId
  selectProductSupplier.value.query.supplierIdNotIn = row.supplierId
  selectProductSupplier.value.index = Number(index)
  selectRow.value = row
  defaultSupplier.value = false
}
//添加产品按钮
function addProduct() {
  const _tableInfo = tableInfo.value
  const _formInfo = formInfo.value
  let idNotIn = _tableInfo.data.map(function (item) {
    return item.productId
  })
  let purchType = _formInfo.data.purchType
  if (purchType === 0) {
    productInfo.value.query.queryParams.orderId = _formInfo.data.id
    productInfo.value.tableKey =
      'purchApplicationDetailForPurchOrder-com.slip.spd.entity.vo.purch.PurchApplicationDetailVO'
    productInfo.value.api = applicationDetailAddProduct
    productInfo.value.query.queryMap.productId.value = idNotIn.toString()
    productInfo.value.query.queryMap.orderId.value =
      _formInfo.data.applicationId
  } else if (purchType === 1) {
    productInfo.value.query.queryParams.orderId = _formInfo.data.id
    productInfo.value.tableKey =
      'purchApplicationSummaryDetailForPurchOrder-com.slip.spd.entity.vo.purch.PurchApplicationSummaryDetailVO'
    productInfo.value.api = applicationSummaryDetailAddProduct
    productInfo.value.query.queryMap.productId.value = idNotIn.toString()
    productInfo.value.query.queryMap.orderId.value =
      _formInfo.data.applicationId
  } else {
    productInfo.value.query.queryMap.id.value = idNotIn.toString()
    productInfo.value.query.queryMap.status.value = 1
    productInfo.value.query.queryParams.deptId = _formInfo.data.deptId
  }
  productInfo.value.query.queryMap.isConsignment.value =
    formInfo.value.data.isConsignBusiness
  productInfo.value.query.queryParams.purchAccording = props.purchAccording
  productInfo.value.visible = true
}
function addProductByContract() {
  contractInfo.value.changeContract = false
  contractInfo.value.data = []
  contractInfo.value.visible = true
}
function selectContractCallBack(data) {
  if (data) {
    if (contractInfo.value.changeContract) {
      tableInfo.value.data[contractInfo.value.selectIndex].contractId = data.id
      tableInfo.value.data[contractInfo.value.selectIndex].quoteContractNo =
        data.orderNo
      tableInfo.value.data[contractInfo.value.selectIndex].price = data.price
      tableInfo.value.data[contractInfo.value.selectIndex].supplierId =
        data.supplierId
      tableInfo.value.data[contractInfo.value.selectIndex].supplierName =
        data.supplierName
      return
    }
    const _data = data.map((item) => {
      item.qty = 0
      item.calcQty = 0
      item.largeUnitQty = 0
      item.smallUnitQty = 0
      item.isConsignBusinessValue = item.isConsignmentValue
      item.isConsignBusiness = item.isConsignment

      return item
    })
    data.map((item) => {
      const contractItem = _.find(tableInfo.value.data, [
        'productId',
        item.productId,
      ])
      if (!contractItem) tableInfo.value.data.push(item)
    })
  }
}
function selectProductCallback(rows) {
  if (rows) {
    rows = generateProductKey(rows)
    let selections = tableInfo.value.selectionsCopy
    let purchType = formInfo.value.data.purchType
    let purchAccording = formInfo.value.data.purchAccording
    if ((purchType === 0 || purchType === 1) && purchAccording === 1) {
      const data = rows.map(function (item) {
        return {
          ...item,
          calcQty: item.calcQty - item.prePurchCalcQty,
          largeUnitQty: parseInt(
            (item.calcQty - item.prePurchCalcQty) / item.unitConvertCoefficient
          ),
          smallUnitQty: parseInt(
            (item.calcQty - item.prePurchCalcQty) % item.unitConvertCoefficient
          ),
          qty: 0,
          price: item.defaultSupplierPrice || 0,
          supplierId: item.defaultSupplierId,
          supplierName: item.defaultSupplierName,
          isConsignBusinessValue: item.isConsignmentValue,
          isConsignBusiness: item.isConsignment,
        }
      })
      if (
        systemConfig.value.use_convert_count_restrict == 1 &&
        formInfo.value.data.useId
      ) {
        data.forEach((item) => {
          if (selections.length) {
            selections.forEach((row) => {
              if (row.productId === item.productId) {
                item.maxConvertCount = row.maxConvertCount
                if (item.calcQty === 0) {
                  item['largeUnitQty'] = parseInt(
                    (item.maxConvertCount || 0) / item.unitConvertCoefficient
                  )
                  item['smallUnitQty'] = parseInt(
                    (item.maxConvertCount || 0) % item.unitConvertCoefficient
                  )
                }
              }
            })
          }
        })
      }
      tableInfo.value.data = data.concat(tableInfo.value.data)
    } else {
      const data = rows.map(function (item) {
        return {
          ...item,
          qty: 0,
          price: item.price || 0,
          defaultSupplierId: item.supplierId,
          defaultSupplierName: item.supplierName,
          defaultSupplierCode: item.supplierCode,
          defaultSupplierPrice: item.price,
          isConsignBusinessValue: item.isConsignmentValue,
          isConsignBusiness: item.isConsignment,
        }
      })
      if (
        systemConfig.value.use_convert_count_restrict == 1 &&
        formInfo.value.data.useId
      ) {
        data.forEach((item) => {
          if (selections.length) {
            selections.forEach((row) => {
              if (row.productId === item.productId) {
                item.maxConvertCount = row.maxConvertCount
                if (item.calcQty === 0) {
                  item['largeUnitQty'] = parseInt(
                    (item.maxConvertCount || 0) / item.unitConvertCoefficient
                  )
                  item['smallUnitQty'] = parseInt(
                    (item.maxConvertCount || 0) % item.unitConvertCoefficient
                  )
                }
              }
            })
          }
        })
      }
      tableInfo.value.data = data.concat(tableInfo.value.data)
    }
  }
}
function generateProductKey(products) {
  return products.map((item) => {
    const key =
      item.productId +
      '&' +
      item.batchNumber +
      '&' +
      item.validityDate +
      '&' +
      item.productionDate
    item._id = key
    return item
  })
}
//删除产品
function removeProduct(item) {
  if (item) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (obj) => obj.productId !== item.productId
    )
    return
  }
  proxy
    .$confirm('删除后将改变数据,是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      tableInfo.value.selectionsCopy = proxy.$fn.deepClone(
        tableInfo.value.selections
      )
      tableInfo.value.data = tableInfo.value.data.filter(
        (row) => !tableInfo.value.selections.includes(row)
      )
    })
}
//打开选择收货地址窗口
function openReceiveAddressWindow() {
  selectReceiveAddressInfo.value.visible = true
}
function selectReceiveAddressCallback(data) {
  const _formInfo = formInfo.value
  if (data) {
    _formInfo.data.receiveAddressValue = data.addressValue
    _formInfo.data.receiveProvince = data.province
    _formInfo.data.receiveCity = data.city
    _formInfo.data.receiveCounty = data.county
    _formInfo.data.receiveAddress = data.address
    _formInfo.data.receiveContacts = data.contacts
    _formInfo.data.receivePhone = data.contactsPhone
  }
}
function selectSupplierCallback(data) {
  if (data) {
    formInfo.value.data.supplierId = data.supplierId
    formInfo.value.data.supplierName = data.supplierName
    tableInfo.value.data = []
  }
}
function selectProductSupplierCallback(data) {
  let selectContract = null
  if (selectRow.value.contractVOList)
    selectContract = _.find(selectRow.value.contractVOList, [
      'supplierId',
      data.supplierId,
    ])
  tableInfo.value.data[selectProductSupplier.value.index] = {
    ...tableInfo.value.data[selectProductSupplier.value.index],
    supplierId: data.supplierId,
    supplierName: data.supplierName,
    contractId: selectContract && selectContract.id,
    quoteContractNo: selectContract && selectContract.orderNo,
    price: data.price,
  }
}
//打开部门弹窗
function openDeptWindow() {
  selectDeptInfo.value.visible = true
}
function selectDeptCallback(data) {
  if (data) {
    if (formInfo.value.data.deptId !== data.id) {
      formInfo.value.data.deptName = data.name
      formInfo.value.data.deptId = data.id
      defaultSelect.value = []
      tableInfo.value.data = []
    }
  } else {
    formInfo.value.data.deptName = ''
    formInfo.value.data.deptId = ''
    defaultSelect.value = []
    tableInfo.value.data = []
  }
}
function save() {
  const _tableInfo = tableInfo.value
  proxy.$fn.checkForm(formRefs.value).then(() => {
    if (!_tableInfo.data.length) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '产品不能为空',
      })
      return
    }
    let newDetails = _tableInfo.data.filter((item) => item.calcQty > 0)
    if (newDetails.length < _tableInfo.data.length) {
      proxy
        .$confirm(`存在数量为0的产品，是否继续保存`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        .then(() => {
          checkSave()
        })
        .catch()
    } else {
      checkSave()
    }
  })
}
function checkSave() {
  const _formInfo = formInfo.value
  const _tableInfo = tableInfo.value
  const details = _tableInfo.data
  const data = _formInfo.data
  data.isSpecialEdit = props.isSpecialEdit
  data.mergeDetails = proxy.$fn.filterBlacklist(details)
  const api = data.id ? updatePurchOrder : createPurchOrder
  api(data).then((resp) => {
    if (resp && resp.success) {
      emits('returnModify', false)
      showDialog.value = false
    }
  })
}
function getPurchOrderById(orderId) {
  purchOrderById(orderId).then((resp) => {
    if (resp && resp.success) {
      if (props.isCopy) {
        formInfo.value.data.deptName = resp.data.deptName
        formInfo.value.data.deptId = resp.data.deptId
        formInfo.value.data.supplierId = resp.data.supplierId
        formInfo.value.data.supplierName = resp.data.supplierName
        formInfo.value.data.isConsignBusiness = resp.data.isConsignBusiness
        formInfo.value.data.isConsignBusinessValue =
          resp.data.isConsignBusinessValue
      } else {
        formInfo.value.data = resp.data
      }
      filterInfo.value.query.queryParams.purchAccording =
        resp.data.purchAccording

      getPurchOrderDetails()
    }
  })
}
function getPurchOrderDetails() {
  purchOrdersDetailCustomizeListAll(filterInfo.value.query).then((resp) => {
    if (resp && resp.success) {
      tableInfo.value.data = resp.data
      tableInfo.value.data.forEach((item) => {
        item.isConsignBusiness = item.isConsignment
        item.isConsignBusinessValue = item.isConsignmentValue
        item.supplierId = formInfo.value.data.supplierId
        item.supplierName = formInfo.value.data.supplierName
        if (props.isCopy) {
          item.orderId = null
          item.storeQty = null
          item.storeCalcQty = null
          item.deliverQty = null
          item.deliverCalcQty = null
          item.supplierRefuseQty = null
          item.supplierRefuseCalcQty = null
          item.supplierReceiveQty = null
          item.supplierReceiveCalcQty = null
          item.price = item.defaultSupplierPrice
          item.refuseQty = 0
          item.refuseCalcQty = 0
          item.supplierName = item.defaultSupplierName
          item.supplierId = item.defaultSupplierId
          item.quoteContractNo = ''
          item.contractId = -2
          if (item.contractVOList && item.contractVOList.length) {
            let contractVOListItem = item.contractVOList.filter(
              (row) => row.supplierId === item.defaultSupplierId
            )
            if (contractVOListItem.length) {
              item.quoteContractNo = contractVOListItem[0].orderNo
              item.contractId = contractVOListItem[0].id
            }
          }
        }
      })
    }
  })
}
function selectOrderChange(data) {
  if (data.length) {
    filterInfo.value.list[0]['disabled'] = true
    filterInfo.value.list[1]['disabled'] = true
    filterInfo.value.handle.btList[0]['show'] = false
    filterInfo.value.fieldList[6]['disabled'] = true
    disabledTemplateBtn.value = true
    defaultSelect.value = data
    let ids = data.map((item) => item.id).toString()
    mergedPurchIds.value = ids
    let params = {
      orderIdIn: ids,
    }
    getOrdersProduct(params).then((res) => {
      if (res) {
        tableInfo.value.data = res.data
      }
    })
  } else {
    filterInfo.value.list[0]['disabled'] = false
    filterInfo.value.list[1]['disabled'] = false
    filterInfo.value.handle.btList[0]['show'] = true
    filterInfo.value.fieldList[6]['disabled'] = false
    disabledTemplateBtn.value = false
    defaultSelect.value = []
    tableInfo.value.data = []
  }
}
function selectTemplate() {
  purchTemplateInfo.value.visible = true
  purchTemplateInfo.value.query.deptId = formInfo.value.data.deptId
  purchTemplateInfo.value.query.templateType = 0
}
function selectPurchTemplateCallback(data) {
  if (data) {
    let ids = data.map((row) => row.id)
    let purchTemplateIds = String(ids)
    const params = {
      purchTemplateIdIn: purchTemplateIds,
      purchAccording: props.purchAccording,
    }
    let selections = tableInfo.value.selectionsCopy
    getPurchTemplateDetailAll(params).then((resp) => {
      if (resp && resp.success) {
        resp.data = resp.data.filter((item) => {
          return tableInfo.value.data.every(
            (el) => el.productId !== item.productId
          )
        })
        if (
          systemConfig.value.use_convert_count_restrict == 1 &&
          formInfo.value.data.useId
        ) {
          resp.data.forEach((item) => {
            if (selections.length) {
              selections.forEach((row) => {
                if (row.productId === item.productId) {
                  item.maxConvertCount = row.maxConvertCount
                  if (item.calcQty === 0) {
                    item['largeUnitQty'] = parseInt(
                      (item.maxConvertCount || 0) / item.unitConvertCoefficient
                    )
                    item['smallUnitQty'] = parseInt(
                      (item.maxConvertCount || 0) % item.unitConvertCoefficient
                    )
                  }
                }
              })
            }
          })
        }
        tableInfo.value.data = resp.data.concat(tableInfo.value.data)
      }
    })
  }
}
function getValueList() {
  getCoreSystemConfigGetConfigValue({
    systemConfigCode: 'license_nearly_effective',
  }).then((resp) => {
    if (resp && resp.success) {
      licencesSystemConfig.value = resp.data
    }
  })
}
function tableRowClassName({ row = undefined }) {
  if (row.licenseEndDate) {
    let dataDiff = proxy.$fn.dateDiffLicen(row.licenseEndDate)
    if (dataDiff <= 0) {
      return 'expire-row'
    } else if (Number(licencesSystemConfig.value) >= dataDiff) {
      return 'nearly-row'
    }
  }
  return ''
}
function tableCellClassName({ column, row }) {
  if (row.calcQty === 0 && column.property === 'qty') {
    return 'cell-color'
  }
  return ''
}
function getCustomize(update = undefined) {
  let _tableInfo = tableInfo.value
  let param = {
    tableKey: props.tableKey,
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      _tableInfo.fieldList = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail
      )
      _tableInfo.fieldList.forEach((item) => {
        if (item.value === 'quoteContractNo') {
          if (formInfo.value.data.purchAccording == 2) {
            item.hidden = false
          } else {
            item.hidden = true
          }
        }
      })

      filterInfo.value.query.customizeUserVO = data
      filterInfo.value.query.queryMap.orderId.value = props.orderId
      if (update) {
        let arr = []
        for (let key in data.detail) {
          arr.push(data.detail[key])
        }
        let sortArr = []
        arr.forEach((item) => {
          if (item.sortControllerType === 1) {
            sortArr.push({
              prop: item.fieldName,
              order: 'ascending',
            })
          } else if (item.sortControllerType === 2) {
            sortArr.push({
              prop: item.fieldName,
              order: 'descending',
            })
          }
        })
        if (sortArr.length) {
          proxy.$refs.table.$refs.table.sort(sortArr[0].prop, sortArr[0].order)
        }
        return
      }
      if (props.orderId) {
        getPurchOrderById(props.orderId)
      }
    }
  })
}
function changeContract(row, index) {
  //打开切换合同弹窗
  contractInfo.value.data = row.contractVOList.filter(
    (item) => item.id !== row.contractId
  )
  if (!contractInfo.value.data.length) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '没有能切换的合同',
    })
    return
  }

  contractInfo.value.visible = true
  contractInfo.value.selectIndex = index
  contractInfo.value.changeContract = true
  contractInfo.value.data = row.contractVOList.filter(
    (item) => item.id !== row.contractId
  )
}
</script>

<style scoped lang="scss">
// :deep(.table-scroll-hidden) > .el-table {
//   overflow-y: hidden;
// }
.model-panel-title {
  display: flex;
  align-items: center;
  .model-tips {
    display: flex;
    align-items: center;
    margin-left: 10px;
    color: #909399;
    .model-tips-nearly,
    .model-tips-expire {
      display: block;
      margin-left: 5px;
      width: 17px;
      height: 17px;
    }
    .model-tips-nearly {
      background: #fceacb;
    }
    .model-tips-expire {
      background: #f5e4e4;
    }
  }
}
:deep(.el-table) {
  .nearly-row {
    background: #fceacb;
  }
  .expire-row {
    background: #f5e4e4;
  }
  .cell-color {
    background: #f4aed9bd;
  }
}
</style>
